<template>
  <el-dialog
    :visible.sync="loginVisible"
    :show-close="false"
    :title="formTitle"
    width="740px"
    append-to-body
    center
    destroy-on-close
    custom-class="jepaas-login-dialog"
  >
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="jepaas-login-ruleForm"
    >
      <el-form-item prop="phone">
        <el-input
          v-model="loginForm.phone"
          placeholder="手机号"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        prop="password"
        style="margin-bottom: 5px;"
      >
        <el-input
          v-if="loginMode"
          v-model="loginForm.password"
          placeholder="密码"
          type="password"
          autocomplete="off"
        />
        <el-input
          v-else
          v-model="loginForm.validateCode"
          class="regPhone"
          placeholder="请输入短信验证码"
          autocomplete="off"
        >
          <el-button
            slot="suffix"
            :disabled="auth_time!=0"
            @click="getCode(loginForm.phone)"
            type="text"
            class="getCode"
          >
            {{ auth_time == 0?"获取验证码":`${auth_time}s重新发送` }}
          </el-button>
        </el-input>
      </el-form-item>
      <el-form-item style="margin-bottom: 60px;">
        <el-checkbox v-model="loginForm.rememberStatus">
          记住状态
        </el-checkbox>
        <span class="handleBtns">
          <el-button
            @click="forgetPsd"
            size="small"
            class="forgetPsd"
            type="text"
          >忘记密码</el-button>
          <el-button
            @click="changeMode"
            size="small"
            type="text"
          >{{ loginMode ? '动态验证码登录' : '个人密码登录' }}</el-button>
        </span>
      </el-form-item>

      <el-form-item style="margin-bottom: 5px;">
        <el-button
          @click="doLogin"
          :loading="isLoginLoading"
          type="danger"
        >
          登 录
        </el-button>
      </el-form-item>
      <el-form-item>
        还没有账户？
        <el-button
          @click="forgetPsd"
          class="registerBtn"
          type="text"
        >
          立即注册
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>

export default {
  name: 'JepaasLoginDialog',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入手机号'));
      }
      if (!(/^1[3456789]\d{9}$/.test(value))) {
        return callback(new Error('手机号格式有误!'));
      }
      callback();
    };
    const validatePass = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入密码'));
      }
      callback();
    };
    const validateCode = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入验证码'));
      }
      callback();
    };
    return {
      loginVisible: false,
      isLoginLoading: false,
      loginForm: {
        phone: '',
        password: '',
        validateCode: '',
        rememberStatus: true,
      },
      loginRules: {
        password: [
          { validator: validatePass, trigger: 'blur' },
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' },
        ],
        validateCode: [
          { validator: validateCode, trigger: 'blur' },
        ],
      },
      formTitle: '登录',
      loginMode: true,
      auth_time: 0, // 登录的获取验证码倒计时
    };
  },
  mounted() {
    this.isLoginPhone(); // 判断是否保存手机号了
  },
  methods: {
    doLogin() {
      this.isLoginLoading = true;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          JE.fetch({
            url: '/jepaas/login/login',
            params: {
              phone: this.loginForm.phone,
              type: this.loginMode ? 'general' : 'dynamic',
              password: this.loginForm.password,
              codeDomo: this.loginForm.validateCode,
            },
          }).then((data) => {
            // 登录成功的时候判断是否记住登录状态了
            if (!data.success) {
              this.isLoginLoading = false;
              return this.$message({
                message: `${data.message}`,
                type: 'error',
              });
            }
            // 网站登录token和开发平台用户ID进行绑定 (id_token) 存cookie
            JE.setCookies('websiteJepaasAuthorization', `${JE.USER.id}_${data.obj}`);
            // 把网站登录token 存入 cookie
            JE.setCookies('jepaasAuthorization', data.obj);
            this.loginStatusNumber();
            this.getUserInfo(); // 获取用户信息
          });
        } else {
          this.isLoginLoading = false;
          return false;
        }
      });
    },
    // 获取用户登录信息
    getUserInfo() {
      JE.fetch({
        url: '/jepaas/login/getUserInfoById',
      }).then((data) => {
        this.isLoginLoading = false;
        if (!data.success) {
          return this.$message({
            message: data.message,
            type: 'error',
          });
        }
        this.$emit('getUserInfo', data.obj);
        this.loginVisible = false;
      });
    },
    // 判断登录是否记住状态了
    loginStatusNumber() {
      if (this.loginForm.rememberStatus) {
        localStorage.setItem('suanban-loginFormPhone', this.loginForm.phone);
      } else {
        // 如果不勾选记住状态的话删除之前的记录
        localStorage.getItem('suanban-loginFormPhone') && localStorage.removeItem('suanban-loginFormPhone');
      }
    },
    // 判断本地是否存储的账号
    isLoginPhone() {
      if (localStorage.getItem('suanban-loginFormPhone')) {
        this.loginForm.phone = localStorage.getItem('suanban-loginFormPhone');
      }
    },
    // 切换方式登录
    changeMode() {
      this.$refs.loginForm.resetFields();
      this.loginMode = !this.loginMode;
    },
    // 忘记密码
    forgetPsd() {
      window.open('http://jepaas.com');
    },
    /**
     * 获取验证码
     * @param phone 当前的手机号
     * @param status 当前验证码倒计时的字段
     */
    getCode(phone) {
      let errMsg = '';
      //  获取验证码的判断手机号是否满足
      // 登录的正则判断
      this.$refs.loginForm.validateField('phone', (error) => {
        if (error) {
          errMsg = error;
        }
      });
      // 不满足任何一项全部返回
      if (!phone || this.auth_time != 0 || errMsg) {
        return;
      }
      JE.fetch({
        url: '/jepaas/login/sendRandom',
        params: {
          phone,
        },
      }).then((data) => {
        if (!data.success) {
          return this.$message({
            message: data.message,
            type: 'error',
          });
        }
        this.$message({
          message: '验证码已发送!',
          type: 'success',
        });
        this.auth_time = 59;
        const auth_timer = setInterval(() => {
          this.auth_time--;
          if (this.auth_time <= 0) {
            clearInterval(auth_timer);
          }
        }, 1000);
      });
    },
  },
};
</script>

<style lang="scss">
.jepaas-login-dialog {
  .el-dialog__header {
    padding-top: 40px;
    .el-dialog__title {
      color: #3f3f3f;
      font-weight: 600;
    }
  }
  .el-dialog__body {
    padding: 20px 120px 40px;
  }
  .jepaas-login-ruleForm {
    .el-input__inner {
      height: 50px;
      line-height: 50px;
    }
    .el-form-item:first-child {
      margin-bottom: 50px;
    }
    .el-checkbox {
      padding-left: 10px;
      .el-checkbox__input {
        position: absolute;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
      }
      .el-checkbox__input.is-checked .el-checkbox__inner {
        background-color: #F6474E;
        border-color: #F6474E;
      }
      .el-checkbox__input.is-checked+.el-checkbox__label {
        color: #3F3F3F;
      }
    }
    .handleBtns {
      float: right;
      .el-button--text {
        color: #A9ABA9;
        &:hover {
          opacity: .8;
        }
      }
    }
    .el-button--danger {
      width: 100%;
      padding: 12px;
      font-size: 16px;
    }
    .getCode {
      line-height: normal;
      padding: 15px 20px;
    }
    .registerBtn {
      color: #376BD0;
      &:hover {
        opacity: .8;
      }
    }
    .forgetPsd {
      position: relative;
      &:after {
        content: ' ';
        position: absolute;
        right: -9px;
        top: 8px;
        height: 12px;
        width: 1px;
        background-color: #d8d8d8;
      }
    }
  }
}
</style>
